<template>
  <div class="app-container">
    <el-row>
      <!-- 树结构 -->
      <el-col :md="5">
        <el-card class="box-card">
          <el-tree
            :data="tree"
            :props="defaultProps"
            :default-expand-all="true"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      <!-- 主内容 -->
      <el-col
        :md="19"
        style="padding-left: 10px"
      >
        <el-row type="flex" class="row-bg" align="middle" justify="space-between">
          <div class="container-title">{{ selectedOrg.name }}</div>
          <!-- 顶部操作 -->
          <div class="filter-container">
            <el-button
              v-permission="['USER_ORG_ORGLIST_ADD_BUTTON']"
              type="success"
              @click="insertChildOrg"
            >添加下级机构</el-button>
            <el-button
              v-permission="['USER_ORG_ORGLIST_EDIT_BUTTON']"
              type="warning"
              @click="updateOrg"
            >修改当前机构</el-button>
            <el-button
              v-permission="['USER_ORG_ORGLIST_DEL_BUTTON']"
              type="danger"
              @click="deleteOrg"
            >删除当前机构</el-button>
          </div>
        </el-row>
      </el-col>
      <!-- 机构dialog -->
      <el-dialog
        width="70%"
        top="5vh"
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        destroy-on-close
        @close="resetTemp"
      >
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-position="right"
          label-width="130px"
        >
          <el-form-item v-if="dialogStatus === 'create'" label="上级机构" prop="orgParentId">
            <el-popover
              v-model="visible"
              placement="bottom-start"
              width="300"
              trigger="click"
            >
              <el-tree
                class="tree"
                width="100%"
                :data="tree"
                :props="defaultProps"
                :default-expand-all="true"
                :expand-on-click-node="false"
                @node-click="selectParentOrg"
              />
              <el-input
                slot="reference"
                :value="parentOrgName"
                :readonly="true"
              />
            </el-popover>
          </el-form-item>

          <el-form-item label="机构名称" prop="orgName">
            <el-input v-model="temp.orgName" />
          </el-form-item>
          <el-form-item label="机构编码" prop="orgCode">
            <el-input v-model="temp.orgCode" />
          </el-form-item>
          <el-form-item label="顺序" prop="orgSort">
            <el-input v-model="temp.orgSort" oninput="value=value.replace(/\D|^[0]+/g,'').slice(0,8)" type="number" min="0" />
          </el-form-item>
          <el-form-item label="备注" prop="orgRemark">
            <el-input v-model="temp.orgRemark" maxlength="100" show-word-limit type="textarea" class="limit" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false"> 取消 </el-button>
          <el-button
            type="primary"
            @click="dialogStatus === 'create' ? createData() : updateData()"
          >
            提交
          </el-button>
        </div>
      </el-dialog>
    </el-row>
  </div>
</template>
<script>
import hrOrganizationApi from '@/framework/api/hrOrganization'
export default {
  name: 'OrgList',
  data() {
    return {
      tree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      visible: false,
      selectedOrg: {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改机构',
        create: '新增机构'
      },
      temp: {
        orgParentId: ''
      },
      parentOrgName: '',
      rules: {
        orgParentId: [{ required: true, message: '选择上级机构', trigger: 'change' }],
        orgName: [{ required: true, message: '请输入机构名称', trigger: 'change' }],
        orgCode: [{ required: true, message: '请输入机构编码', trigger: 'change' }],
        orgSort: [{ required: true, message: '请输入机构顺序', trigger: 'change' }]
      }
    }
  },
  created() {
    this.initTree()
  },
  methods: {
    initTree() {
      const that = this
      hrOrganizationApi.fetchList().then((res) => {
        that.tree = res.data
        that.selectedOrg = res.data[0]
      })
    },
    handleNodeClick(data) {
      this.selectedOrg = data
      this.selectedOrg.orgId = data.id
    },
    selectParentOrg(data) {
      this.visible = false
      this.temp.orgParentId = data.id
      this.parentOrgName = data.name
    },
    resetTemp() {
      this.temp = {
        orgParentId: ''
      }
      this.parentOrgName = ''
    },
    insertChildOrg() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.temp.orgParentId = this.selectedOrg.orgId
      this.parentOrgName = this.selectedOrg.name
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 创建用户请求
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          hrOrganizationApi.add(tempData).then((res) => {
            if (res.success) {
              this.initTree()
              this.dialogFormVisible = false
              this.$message({
                title: '成功',
                message: '新增成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$message({
                title: '失败',
                message: res.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    // 修改用户请求
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          hrOrganizationApi.edit(tempData).then((res) => {
            if (res.success) {
              this.initTree()
              this.dialogFormVisible = false
              this.$message({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$message({
                title: '失败',
                message: res.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    updateOrg() {
      const that = this
      this.dialogStatus = 'update'
      hrOrganizationApi.detail(this.selectedOrg.id).then((res) => {
        that.temp = Object.assign({}, res.data)
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    deleteOrg() {
      this.$confirm('确定要删除“' + this.selectedOrg.name + '”吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        hrOrganizationApi.delete(this.selectedOrg).then(res => {
          if (res.success) {
            this.initTree()
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$message({
              title: '失败',
              message: res.message,
              type: 'error',
              duration: 2000
            })
          }
        })
      }).catch(() => {
        // 取消不做操作
      })
    }

  }
}
</script>
<style lang="scss" scoped>
.container-title{
        font-size: 30px;
        line-height: 46px;
        font-weight: bold;
    }
</style>
